package com.yanqu.road.server.cmd.union.cross.parergon;

import com.yanqu.road.entity.player.UserInfo;
import com.yanqu.road.entity.union.UnionInfo;
import com.yanqu.road.entity.union.parergon.UnionParergonOperateResult;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.pb.union.Parergon;
import com.yanqu.road.server.cmd.base.AbstractCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.command.CmdApi;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.manger.config.UnionConfigMgr;
import com.yanqu.road.server.manger.union.CrossUnionMgr;
import com.yanqu.road.server.manger.union.UnionParergonMgr;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.string.StringUtils;

@CmdApi(reqMsg = Parergon.OperateReqMsg.class, respMsg = Parergon.OperateRespMsg.class)
@Cmd(code = Protocol.S_UNION_PARERGON_OPERATE, desc = "点击经营")
public class OperateCmd extends AbstractCommand {

    private int parergonId;

    private int type;

    private int operateTimes;

    private UnionParergonOperateResult operateResult = new UnionParergonOperateResult();

    @Override
    public boolean parseData(YanQuMessage packet) throws Exception {
        Parergon.OperateReqMsg reqMsg = Parergon.OperateReqMsg.parseFrom(packet.getBytes());
        parergonId = reqMsg.getParergonId();
        type = reqMsg.getType();
        operateTimes = reqMsg.getOperateTimes();
        return true;
    }

    @Override
    public void execute(GamePlayer player, YanQuMessage packet) throws Exception {

        UserInfo userInfo = player.getUserInfo();
        String unionUid = userInfo.getUnionUid();
        if (StringUtils.isNullOrEmpty(unionUid)) {
            ret = GameErrorCode.E_PARERGON_NOT_IN_UNION;
            return;
        }
        UnionInfo unionInfo = CrossUnionMgr.getUnionInfo(unionUid);
        int unionLevel = UnionConfigMgr.getUnionLv(unionInfo.getExperience());
        if(type == 1 && GameConfig.PARERGON_ONE_KEY_OPERATE_UNION_LV > unionLevel){
            ret = GameErrorCode.E_UNION_LEVEL_NO_ENOUGH;
            return;
        }

        Parergon.OperateReqMsg.Builder crossReq = Parergon.OperateReqMsg.newBuilder();
        crossReq.setType(type);
        crossReq.setParergonId(parergonId);
        crossReq.setOperateTimes(operateTimes);
        player.sendPacket(Protocol.C_UNION_PARERGON_OPERATE, crossReq);
    }

    @Override
    public void sendData(GamePlayer player) {
        if(ret != 0){
            operateResult = new UnionParergonOperateResult();
            operateResult.setRet(ret);
            player.sendPacket(Protocol.U_UNION_PARERGON_OPERATE, UnionParergonMgr.builderOperateRespMsg(operateResult));
        }
    }

}
